package com.edu.lxshpc.handler;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.edu.lxshpc.utils.MyException;
import com.edu.lxshpc.utils.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zgh
 * @date 2023/10/28
 * 认证失败处理器
 */
@Component
@Slf4j
public class MyFailurHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("进入自定义登陆失败处理器");
        String username = request.getParameter("username");
        Result result = new Result();
        if (e instanceof AccountExpiredException) {
            // 账号过期
            log.info("[登录失败] - 用户[{}]账号过期", username);
             result.setMessage("登陆失败:账号已过期" );
        }
        if (e instanceof BadCredentialsException) {
            // 密码错误
            log.info("[登录失败] - 用户[{}]密码错误", username);
             result.setMessage("登陆失败:密码错误");
        }
        if (e instanceof CredentialsExpiredException) {
            // 密码过期
            log.info("[登录失败] - 用户[{}]密码过期", username);
             result.setMessage("登陆失败:密码过期" );
        }
        if (e instanceof DisabledException) {
            // 用户被禁用
            log.info("[登录失败] - 用户[{}]被禁用", username);
             result.setMessage("登陆失败:此账号已被禁用");
        }
        if (e instanceof LockedException) {
            // 用户被锁定
            log.info("[登录失败] - 用户[{}]被锁定", username);
             result.setMessage("登陆失败:此账号已被锁定");
        }
        if (e instanceof InternalAuthenticationServiceException) {
            // 内部错误
            log.error(String.format("[登录失败] - [%s]内部错误", username), e);
            result.setMessage("登陆失败:其他错误" );
        }
        String s = JSONUtil.toJsonStr(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(s);
        response.getWriter().flush();
    }
}
